package com.cqjtu.eecs.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cqjtu.eecs.entity.Role;
import com.cqjtu.eecs.entity.params.role.RoleParams;
import com.cqjtu.eecs.entity.vo.RolePermissionVO;
import com.cqjtu.eecs.exception.ParamsErrorException;
import com.cqjtu.eecs.service.IRoleService;
import com.cqjtu.eecs.utils.Assert;
import com.cqjtu.eecs.utils.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 角色 前端控制器
 * </p>
 *
 * @author  luojun
 * @since 2022-03-04
 */
@RestController
@RequestMapping("/role")
@Api(tags = "角色接口")
public class RoleController {
    @Autowired
    private IRoleService roleService;

    @ApiOperation("获取全部角色")
    @GetMapping("/queryAll")
    public List<String> listRoleList(){
        ArrayList<String> strings = new ArrayList<>();
        List<Role> list = roleService.list();
        list.forEach(item -> {
            strings.add(item.getRoleName());
        });
        return strings;
    }
    @ApiOperation("获取全部角色（含id）")
    @GetMapping("/query")
    public List<Role> listRole(){
        List<Role> list = roleService.list();
        return list;
    }

    @ApiOperation("通过角色名获取角色的权限(树形)")
    @GetMapping("/query/{name}")
    public List<RolePermissionVO> queryRolePermissionByName(@PathVariable("name")String name){
        Assert.notBlank(name, new ParamsErrorException("The name can not be null or blank"));
        return roleService.queryRolePermissionByName(name);
    }
    @ApiOperation("修改角色的权限")
    @PutMapping("/update/{name}")
    public Result updateRolePermission(@PathVariable("name")String name ,@RequestBody List<String> permissions){
        Assert.notBlank(name, new ParamsErrorException("The name can not be null or blank"));
        Assert.notNull(permissions, new ParamsErrorException("The permissionList can not be null"));
        if (roleService.updateRolePermission(name, permissions))
            return Result.success();
        return Result.error();
    }
    @ApiOperation("添加角色")
    @PostMapping("/add")
    public Result addRole(@Valid @RequestBody RoleParams roleParams){
        if (roleService.addRole(roleParams))
            return Result.success();
        return Result.error();
    }

    @ApiOperation("根据角色名获取角色")
    @GetMapping("/getByName/{name}")
    public Role getByName(@PathVariable("name")String name){
        Assert.notBlank(name,new ParamsErrorException("The name can not be null or blank"));
        return roleService.getOne(new LambdaQueryWrapper<Role>().eq(Role::getRoleName, name));
    }
}
